package com.mycookbook;


import java.io.ByteArrayOutputStream;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.provider.MediaStore.Images;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
 
public class RecipeActivity extends FragmentActivity {
    private MyAdapter mAdapter;
    private ViewPager mPager;
    private static final String TAG = "LOL";
    private Uri currImageURI;
    private static String recipeName;
    private String recipeImageUrl;
    
	private static int TAKE_PICTURE = 1;
	private Uri outputFileUri;
	private Button takePicture_button;
    
    static DatabaseHandler db;
 
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        ApplicationData d = ((ApplicationData)getApplicationContext());
        
        db = d.GetDatabase();
        
        recipeName = (String)getIntent().getStringExtra("recipe");
        //recipeImageUrl = db.getImageUrl(recipeName);
        Log.i("LOL", recipeName);
        Recipe testrecipe = db.getRecipeByName(recipeName);
        recipeImageUrl = testrecipe.getImagePath();
        
        Log.i(TAG, "====================================");
        Log.i(TAG, "MainActivity onCreate()");
        setContentView(R.layout.mainrecipefrag);
        Log.i("test", "onCreate");
        mAdapter = new MyAdapter(getSupportFragmentManager(), this);
        mAdapter.setRecipeName(recipeName);
        mAdapter.setImageUrl(recipeImageUrl);
        
        mPager = (ViewPager) findViewById(R.id.pager);
        mPager.setAdapter(mAdapter);
        mPager.setOffscreenPageLimit(3);    
    }
    
    //===== Camera =====//
	private String NameOfFile()
	{
		Calendar calendar = Calendar.getInstance();
		Date date = calendar.getTime();
		SimpleDateFormat format = new SimpleDateFormat("ddMMyyyy-HHmmss");
		String formattedDate = format.format(date);
		
		return formattedDate;
	}
    
	// finder stien til URI'en
	public String getRealPathFromURI(Uri contentUri) {
        String[] proj = { MediaStore.Images.Media.DATA };
        Cursor cursor = managedQuery(contentUri, proj, null, null, null);
        int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        return cursor.getString(column_index);
    }
	
    public void onClickTakePicture(View v)
    {
		try
		{
			Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
			File filedir = new File(Environment.getDataDirectory() + "/MyCookBook/");
			filedir.mkdirs();
			File file = new File(filedir, NameOfFile() + ".jpg");
			
			
			outputFileUri = Uri.fromFile(file);
			//Recipe rep = db.getRecipeByName(recipeName);
			//rep.setImagePath(outputFileUri.toString());
			ImageFragment.UpdateImageUrl(outputFileUri.toString(), recipeName);
			
			startActivityForResult(intent, TAKE_PICTURE);
			Log.i(TAG, "onCickTakePicture()");
			
		
		}
		catch(Exception e)
		{
			ShowMessage("Fail at TakePhoto()");
		}
    }
   
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data)
	{
		if (requestCode == TAKE_PICTURE)
		{
			//Saving URI
			    currImageURI = data.getData();
	
	            int height = 640;
	            int width = 480;    
	           
	            //decode
	            Bitmap bitmap = null;
	            BitmapFactory.Options options = new BitmapFactory.Options();
	            options.inJustDecodeBounds = true;
	            BitmapFactory.decodeFile( getRealPathFromURI(currImageURI), options );
	            if ( options.outHeight > 0 && options.outWidth > 0 ) {
	                options.inJustDecodeBounds = false;
	                options.inSampleSize = 2;
	                while (    options.outWidth  / options.inSampleSize > width
	                        && options.outHeight / options.inSampleSize > height ) {
	                    options.inSampleSize++;
	                }
	                options.inSampleSize--;

	                bitmap = BitmapFactory.decodeFile( getRealPathFromURI(currImageURI), options );
	                if ( bitmap != null ) {
	                    bitmap = Bitmap.createScaledBitmap( bitmap, width, height, false );
	                }
	            }
	        // gemmer billedet currImage i imagefragmentetvariablen imageUrl     
	        ByteArrayOutputStream bytes = new ByteArrayOutputStream();
	        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
	        String path = Images.Media.insertImage(getContentResolver(), bitmap, NameOfFile(), null);
	        
	        
	        //ImageFragment.ImageUrl = path;
	        
			
			
			Log.i(TAG, "IF onActivityResult");
			
			//Opdaterer billedet i Imagefragmentet lige efter billedet er taget
			//ImageFragment.ImageURI(ImageFragment.ImageUrl.toString());
			ImageFragment.ImageURI(path);
		}
		
		Log.i(TAG, "onActivityResult()");
	}
    
	private void ShowMessage(String string)
	{
		Toast.makeText(this, string, Toast.LENGTH_SHORT).show();
	}
	
	public static String getImgUri() {
		Recipe rep = db.getRecipeByName(recipeName);
		String imageUri = db.getImageUrl(rep.getName());
		return imageUri;
	}
	
    
    @Override
	protected void onDestroy() {
		super.onDestroy();
		Log.i(TAG, "onDestroy()");
	}
    
    public void onClickShare(View v){    	
        Recipe rep = db.getRecipeByName(recipeName);
        
        Uri uri = Uri.parse(db.getImageUrl(rep.getName()));
        
        Toast.makeText(this, uri.toString(), Toast.LENGTH_SHORT).show();
        mAdapter.setImageUrl(db.getImageUrl(rep.getName()));
        Intent iEmail = new Intent(Intent.ACTION_SEND);
		iEmail.setType("image/jpg");
		iEmail.putExtra(Intent.EXTRA_STREAM, uri);
		iEmail.putExtra(android.content.Intent.EXTRA_SUBJECT, rep.getName());  
		iEmail.putExtra(android.content.Intent.EXTRA_TEXT, rep.getApproach());
		startActivity(Intent.createChooser(iEmail,"Email:"));
		Log.i(TAG, "onClickShare()");
    }
    
    public void onClickEditRecipe(View v){
    	//Extract data to send
    	Recipe rep = db.getRecipeByName(recipeName);
    	String imageUri = db.getImageUrl(rep.getName());
    	//String imageUri = db.getImageUrl(rep.getImagePath());
    	String name = rep.getName();
    	String approach = rep.getApproach();
    	String category = rep.getCategory();
    	String id = String.valueOf(rep.getID());
    	
    	Intent iIntentToModifyRecipe = new Intent();
    	iIntentToModifyRecipe.setClass(this, ModifyRecipeActivity.class);
    	iIntentToModifyRecipe.putExtra("modify", "ModifyRecipe");
    	iIntentToModifyRecipe.putExtra("imageUri", imageUri);
    	iIntentToModifyRecipe.putExtra("name", name);
    	iIntentToModifyRecipe.putExtra("appraoch", approach);
    	iIntentToModifyRecipe.putExtra("category", category);
    	iIntentToModifyRecipe.putExtra("id", id);
    	
		startActivity(iIntentToModifyRecipe);
    	
    }
    
   
}